from django.contrib.auth.decorators import login_required
from django.db.models import Sum, F, Subquery, OuterRef
from django.http import JsonResponse
from django.shortcuts import render

from res.models import Resource
from .models import UserScore, UserInfo
from django.core.paginator import Paginator
from DjangoProject.db import DBUtils


@login_required
def personal(request):
    # 获取当前登录的用户信息

    info = UserInfo.objects.filter(user=request.user).select_related("user").first()

    sql = """
          select sum(fans) fans, sum(attach) attach
          from (select count(1) fans, '' attach
                from tb_fans
                where user_id = %s
                union all
                select count(1), ''
                from tb_fans
                where fans_id = %s
                  and is_mutual = 1
                union all
                select '' fans, count(1) attach
                from tb_fans
                where fans_id = %s
                union all
                select '', count(1)
                from tb_fans
                where user_id = %s
                  and is_mutual = 1) t \
          """

    user_id = request.user.id
    data = DBUtils.select_one(sql, [user_id] * 4)

    # 根据 remark 分组统计用户积分数量
    echarts_data = UserScore.objects.filter(user=
                                            request.user).values(name=F('remark')).annotate(value=Sum('score'))

    return render(request, 'personal.html', {"info": info, "fansAttach": data, "echarts_data": list(echarts_data)})


@login_required
def score_list(request):
    # 获取页码
    page_number = int(request.GET.get('page', "1"))
    # 获取每页显示条数
    rows = int(request.GET.get('rows', "10"))

    # 查询用户积分列表
    queryset = (UserScore.objects.values("id", "score", "remark", "res_id", "create_time").filter(user=
        request.user).annotate(resource_name=Resource.objects.values('name').filter(pk=
                       OuterRef("res_id"))).order_by("-pk"))

    # 进行分页查询
    paginator = Paginator(queryset, rows)
    # 查询设置第几页的数据、获取page 对象
    page = paginator.get_page(page_number)

    # 获取当前页的数据 和 总页数
    data = list(page.object_list)
    pages = page.paginator.num_pages

    return JsonResponse({"code": 200, "pages": pages, "list": data})
